package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

/*
   Author: mahaiyuan
   Date: 2021/6/4 8:03 下午
   Description:
*/
func main() {
	http.HandleFunc("/hello", hello)
	http.HandleFunc("/student/get", studentGet)
	http.HandleFunc("/student/create", studentCreate)
	http.ListenAndServe("127.0.0.1:8888", nil)
}

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("remoteAddr=%s, method=%s, path=%s\n", r.RemoteAddr, r.Method, r.URL.Path)
	fmt.Printf("body=%s\n", r.Body)
	w.Write([]byte("world你好world你好world你好world你好world你好world你好world你好world你好world你好world你好world你好"))
}

// Get请求
func studentGet(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	params := r.URL.Query()	//获取请求参数 数据格式为 map[string][]string
	id := params["id"][0]
	name := params["name"][0]
	data := map[string]interface{}{
		"errNo":  0,
		"errMsg": "succ",
		"data":   map[string]interface{}{"id": id, "name": name},
	}
	bytes, _ := json.Marshal(data)
	w.Write(bytes)
}
// post请求
func studentCreate(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	switch r.Header.Get("Content-Type") {
		case "application/json":
			studentCreateJson(w, r)
		case "application/x-www-form-urlencoded":
			studentCreateForm(w, r)
	}

	
}

func studentCreateJson(w http.ResponseWriter, r *http.Request) {
	bytes, err := ioutil.ReadAll(r.Body) //读取请求体
	if err != nil {
		fmt.Println("read request data error.", err)
		return
	}
	fmt.Println("request data is :", string(bytes))
	data := map[string]interface{}{
		"errNo":  0,
		"errMsg": "succ",
		"data":   string(bytes),
	}
	res, _ := json.Marshal(data)
	w.Write(res)
}
func studentCreateForm(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	studentNo := r.PostForm.Get("studentNo")
	name := r.PostForm.Get("name")
	fmt.Printf("studentNo=%s, name=%s\n", studentNo, name)
	data := map[string]interface{}{
		"errNo":  0,
		"errMsg": "succ",
		"data": map[string]string{"studentNo": studentNo, "name": name},
	}
	res, _ := json.Marshal(data)
	w.Write(res)
}